# -*- coding: utf-8 -*-
"""
klacfy.py - 电教员的桌面自动整理脚本

Created on Mon Feb 14 19:55:24 2022

@author: Zjl37
"""

"""
Copyright © 2022 Zjl37

本程序是自由软件，以GNU通用公共许可证（GNU General Public License）第三版或更高版本（随你选择）许可。只要遵循许可证条款的要求，你可以自由地修改与分发本软件。
本软件绝对不带任何担保。
你应当已经收到一份GNU通用公共许可证的副本。若没有，请访问 <https://gnu.org/licenses/gpl.txt>。
"""


import os
import re
import time
import shutil
from kc_schedule import scheduleBase
from kc_config import kc_config as cfg
from kc_keyword import excludeList, kwList
srcDir = cfg['srcDir']
destDir = cfg['destDir']


def is_exclude(s: str) -> bool:
    for p in excludeList:
        if re.search(p, s):
            return True
    return False


def eval_catagory_kw(s: str, d: dict):
    for p, c, v in kwList:
        if re.search(p, s):
            d[c] = d.get(c, 0) + v


def strip_date(t: time.struct_time):
    return time.struct_time((1900, 1, 1) + t[3:])


def eval_catagory_date(fn: str, d: dict):
    for _, s in scheduleBase.items():
        ct = time.localtime(os.path.getctime(fn))
        if ct < s['since'] or ct >= s['until']:
            continue
        if ct.tm_wday not in s['lessons']:
            continue
        for p, subject in s['lessons'][ct.tm_wday].items():
            if p not in s['time-periods']:
                continue
            if s['time-periods'][p][0] <= strip_date(ct) < s['time-periods'][p][1]:
                d[subject] = d.get(subject, 0) + s['convinceness']


def determine_catagory(d: dict) -> str:
    l = sorted(d.items(), key=(lambda x: x[1]), reverse=True)
    if len(l) == 0:
        return ''
    if len(l) == 1:
        return '' if l[0][1] < 10 else l[0][0]
    return '' if l[0][1] - l[1][1] < 5 or l[0][1] < 10 else l[0][0]


def klacfy(l: list):
    flog = open('klacfy.log', 'a')
    now = time.time()
    flog.write('\n===== klacfy 启动于 {} =====\n'.format(
        time.asctime(time.localtime(now))))
    for name in l:
        if is_exclude(name):
            continue
        fullname = srcDir + '/' + name

        ct = os.path.getctime(fullname)
        mt = os.path.getmtime(fullname)
        天 = 24*60*60

        if now - ct <= 5*天 or now - mt <= 3*天:
            continue

        d = {}
        if '禁用关键词检测' not in cfg:
            eval_catagory_kw(name, d)
        if '禁用创建日期检测' not in cfg:
            eval_catagory_date(fullname, d)
        cat = determine_catagory(d)
        if cat == '':
            flog.write('无法判断文件 "{:s}" 的类别，理由：{}\n'.format(name, d))
        elif cat in destDir:
            flog.write('将文件 "{:s}" 分类为 "{:s}"\n'.format(name, cat))
            try:
                shutil.move(fullname, destDir[cat])
            except Exception:
                flog.write('[!] 出错了，无法移动该文件。\n')

    flog.close()


if __name__ == '__main__':
    if '停用' in cfg:
        exit()
    klacfy(os.listdir(srcDir))
